#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
import sys
import psutil
import time
from decimal import Decimal
from env import sysConf
import threading
import urllib
import urllib2
import logging

logger = logging.getLogger(__name__)


# 获取空闲内存
def getfreemem():
    try:
        return str(psutil.virtual_memory().free / 1024)
    except:
        logger.error('freememError')
        return ''


# 获取磁盘占用率
def getpercent():
    try:
        return str(psutil.disk_usage('/').percent)
    except:
        logger.error('percentError')
        return ''


# 获取CPU使用率
def getcpuidle():
    try:
        psutil.cpu_percent(None)
        time.sleep(3)
        return str((100 - psutil.cpu_percent(None)))
    except:
        logger.error('cpuidleError')
        return ''


# 获取IO使用率
def getioutil():
    try:
        a = time.time()
        abt = psutil.disk_io_counters().write_count
        time.sleep(1)
        b = time.time()
        bbt = psutil.disk_io_counters().write_count
        return str(Decimal((bbt - abt) / (b - a)).quantize(Decimal('0.0')))
    except:
        logger.error('ioutilError')
        return ''


# 获取PING延迟
def getping():
    try:
        res = ''
        backinfo = os.popen(
            "ping %s -c 1 | sed -n '2p' | awk -F 'time=' '{print $2}'" %
            sysConf[u'rest_host']).readlines()
        if backinfo:
            res = str(backinfo[0].strip())
        return res
    except:
        logger.error('pingError')
        return ''


# 获取主机名称
def gethostname():
    issue = os.popen('cat /etc/issue').read()
    return issue.strip()


class restProgress(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.running = True
        self.sn = sysConf[u'sn']
        self.rest_url = '/systemhealth'

    def exitProcess(self):
        self.running = False
        logger.error('exitProcess')

    def rest_sub(self):
        data = {
            "sn": self.sn,
            "hostname": gethostname(),
            "pingtime": getping(),
            "diskusage": getpercent(),
            "freemem": getfreemem(),
            "cpuidle": getcpuidle(),
            "ioutil": getioutil()
        }
        try:
            request = urllib2.Request('http://{}:{}{}'.format(
                sysConf[u'rest_host'], sysConf[u'rest_port'], self.rest_url))
            r = urllib2.urlopen(request, urllib.urlencode(data))
            logger.info(r.read())
        except urllib2.URLError:
            logger.error("urlopen error [Errno 11001] getaddrinfo failed")

    def run(self):
        logger.info("restprogress running ...")
        while self.running:
            try:
                self.rest_sub()
                time.sleep(30)
            except:
                logger.error(sys.exc_info())
            callable
